﻿define([
	'jquery',
	'underscore',
	'backbone',
	'catjs/util',
	'weibo',
	'library',
	'dorm',
	'canteen',
	'teach',
	'catjs/String'
],function($,_,Backbone,util,weibo,library,dorm,canteen,teach){
	var module = {};

	var DIRECTIONS = ['north','south','west','east'];
	var PATH_BUILDING_NUM = {'n':1,'s':0,'w':2,'e':2,'ns':3,'we':5};
	var NODE_HOR_NUM = 9;//水平节点数量
	var CROSS_SIDE = 108;//十字路口边长常量
	var VERTICAL_RATIO = 1/3;//垂直n,s道路比
	var HORIZONTAL_RATIO = 1/2;//水平w,s道路比

	//节点模型
	var Node = Backbone.Model.extend({

		url : function(){
			var base = '/Node/Default';
			//POST
			if( this.isNew() ){
				return base;
			}else{//GET,UPDATE,DELETE
				return base + '/' + this.id;
			}
		},

		//初始化
		init : function(){
			this.calculate();
		},
		calculate : function(){
			var node = this.attributes;
			node.nearby = [];
			node.paths.forEach(function(path){
				//创建rows
				Object.getOwnPropertyNames(PATH_BUILDING_NUM).indexOf(path.type) === -1 ? 
					0 : path.rows = this.sortfill(path.buildings,PATH_BUILDING_NUM[path.type]);
				//创建marks
				path.marks = this.createMarks(path);
				//相邻节点
				DIRECTIONS.forEach(function(direction){
					if( path[direction] != null ){
						node.nearby.push(direction);
					}
				});

			},this);
			return node;
		},


		//创建空建筑及排序
		sortfill : function(buildings,num){
			var rows = [
				{type:0,style:'',buildings:[]},
				{type:1,style:'',buildings:[]},
			];
			rows.forEach(function(row){
				for (var i = 0; i < num ; i++) {
					row.buildings.push(
						{building_id:undefined,name:undefined,type:'empty'}
					);
				};
			});
			buildings.forEach(function(building){
				//通过arrange对building排序,同时为缺失的arrange增加empty building
				var rowId = 0;
				if( building.arrange >= num ){
					rowId = 1;
				}
				var b = rows[rowId].buildings[building.arrange-num*rowId];

				b.building_id = building.building_id;
				b.name = building.name;
				b.type = building.type;
			});
			return rows;
		},

		//创建路标
		createMarks : function(path){

			var marks = [];
			DIRECTIONS.forEach(function(direction){
				if( path[direction] != null ){
					marks.push({
						type:direction[0].toUpperCase(),
					});
				}
			});
			return marks;
		}

	});//#!Node

	//节点列表模型
	var Nodes = Backbone.Collection.extend({

		model : Node,

		//从服务器加载节点
		loadNode : function(node_id){
			var self = this;
			//若节点已在缓存,直接加载该节点的相邻节点
			if( self.cache.indexOf(node_id) !== -1 ){
				self.cacheNearNode(self.get(node_id).attributes);
				return;
			}

			self.__loadNode(node_id,function(node){
				self.cacheNearNode(node);
			});
		},
		//内部使用,避免对缓存节点进行缓存
		__loadNode : function(node_id,callback){
			var self = this;

			var node = new Node({id:node_id});
			node.fetch({
				success : function(model,response){
					model.init();
					self.add(model);
					self.cache.push(node_id);
					callback === undefined ? 0 : callback(model.attributes);
				},
			});
		},
		cache : [],
		//缓存相邻节点
		cacheNearNode : function(node){
			var self = this;
			node.paths.forEach(function(path){
				DIRECTIONS.forEach(function(direction){
					if( path[direction] != null && self.cache.indexOf(path[direction]) === -1 ){
						self.__loadNode(path[direction]);
					}
				});
			});
		},
	});//#!Nodes

	//当前节点id
	module.current_node = undefined;
	module.NODE_HOR_NUM = NODE_HOR_NUM;
	//节点视图
	var MapView = Backbone.View.extend({

		current_node : undefined,
		template : $('#tplNode').text(),
		maplayer : $('.maplayer'),

		el : $('.mapcanvas'),

		events : {
			'click .road-mark' : 'clickMove',
			//建筑物微博列表
			'click .building .building-weibolist' : 'showBuildingWeiboList',
			//进入图书馆
			'click .building.lib,.building.new_lib,.building.old_lib' : 'enterLib',
			//宿舍
			'click .building.dorm' : 'enterDorm',
			//食堂
			'click .building.canteen' : 'enterCanteen',
			//教学楼
			'click .building.teach' : 'enterTeach',
		},

		initialize : function(){
			this.model.bind('add',this.addNode,this);

		},

		render : function(node){
			this.setSize();
			var nodeLeft = this.totalWidth * (node.node_id % NODE_HOR_NUM);
			var nodeTop = this.totalHeight * parseInt( node.node_id/NODE_HOR_NUM );
			node.style = 'width:{0}px;height:{1}px;left:{2}px;top:{3}px;'.format(this.totalWidth,this.totalHeight,nodeLeft,nodeTop);
			node.paths.forEach(function(path){
				this.pathStyle(path);
			},this);

			var nodeView = $(util.ejs.render( this.template , node ));
			this.$el.append( nodeView );

			//加载微博
			weibo.loadWeibo(node,nodeView);
		},
		//进入图书馆
		enterLib : function(){
			library.enter();
		},
		//进入宿舍
		enterDorm : function(e){
			var dorm_id = e.toElement.dataset.id;
			dorm.enter(dorm_id);
		},
		//进入食堂
		enterCanteen : function(e){
			var can_id = e.toElement.dataset.id;
			canteen.enter(can_id);
		},
		//进入教学楼
		enterTeach : function(e){
			var teach_id = e.toElement.dataset.id;
			teach.enter(teach_id);
		},
		//显示建筑物微博列表
		showBuildingWeiboList : function(e){
			var building_id = e.toElement.href.split('#!')[1];
			weibo.showBuildingWeiboList(building_id);
		},
		//起始显示位置
		startAt : function(node_id){
			this.current_node = node_id;
			module.current_node = this.current_node;
			this.setSize();
            this.maplayer.scrollTop(this.totalHeight * parseInt( ( node_id / NODE_HOR_NUM )));
            this.maplayer.scrollLeft(this.totalWidth * ( node_id % NODE_HOR_NUM ));
		},
		//设置窗口大小
		setSize : function(){
			//计算style
			this.totalWidth = window.innerWidth;
			this.totalHeight = window.innerHeight;
			this.right = parseInt( (this.totalWidth - CROSS_SIDE)*HORIZONTAL_RATIO );
			this.bottom = parseInt( (this.totalHeight - CROSS_SIDE)*VERTICAL_RATIO );
			//修改maplayer style
			$('#viewport .maplayer').css({
				width : this.totalWidth,
				height : this.totalHeight,
			});
		},
		//path css style
		pathStyle : function(path){
			switch(path.type){
				case 'n':
					path.style = 'right:{0}px;height:{1}px;'.format( this.right , this.totalHeight-CROSS_SIDE-this.bottom );
					break;
				case 's':
					path.style = 'right:{0}px;height:{1}px;'.format( this.right , this.bottom );
					break;
				case 'w':
					path.style = 'bottom:{0}px;width:{1}px;'.format( this.bottom , this.totalWidth-CROSS_SIDE-this.right );
					break;
				case 'e':
					path.style = 'bottom:{0}px;width:{1}px;'.format( this.bottom , this.right );
					break;
				case 'ns':
					path.style = 'right:{0}px;height:{1}px;'.format( this.right , this.totalHeight );
					break;
				case 'we':
					path.style = 'bottom:{0}px;width:{1}px;'.format( this.bottom , this.totalWidth );
					break;
				case 'cross':
					path.style = 'right:{0}px;bottom:{1}px;'.format( this.right , this.bottom );
					break;
			}
		},
		//事件监听
		addNode : function(model){
			this.render(model.attributes);
		},
		moveNorth : function(){
			this.current_node = this.current_node - NODE_HOR_NUM;
			module.current_node = this.current_node;
			var properties = {};
			properties.scrollTop = '-='+this.totalHeight;
			this.model.loadNode(this.current_node);
			this.maplayer.animate(properties,1000,'swing');
		},
		moveSouth : function(){
			this.current_node = this.current_node + NODE_HOR_NUM;
			module.current_node = this.current_node;
			var properties = {};
			properties.scrollTop = '+='+this.totalHeight;
			this.model.loadNode(this.current_node);
			this.maplayer.animate(properties,1000,'swing');
		},
		moveWest : function(){
			this.current_node = this.current_node - 1;
			module.current_node = this.current_node;
			var properties = {};
			properties.scrollLeft = '-='+this.totalWidth;
			this.model.loadNode(this.current_node);
			this.maplayer.animate(properties,1000,'swing');
		},
		moveEast : function(){
			this.current_node = this.current_node + 1;
			module.current_node = this.current_node;
			var properties = {};
			properties.scrollLeft = '+='+this.totalWidth;
			this.model.loadNode(this.current_node);
			this.maplayer.animate(properties,1000,'swing');
		},
		clickMove : function(e){
			var type = e.toElement.className.split(' ')[1].slice(-1);
			switch( type ){
				case 'N':
					this.moveNorth();
					break;
				case 'S':
					this.moveSouth();
					break;
				case 'W':
					this.moveWest();
					break;
				case 'E':
					this.moveEast();
					break;
			}

		},

	});//#!MapView

	module.create = function(node_id){

		var nodes = new Nodes;
		var map = new MapView({model:nodes});

		nodes.loadNode(node_id);
		map.startAt(node_id);
	};

	//初始位置
	//图书馆
//	module.init_location = 92;
	//正门
	module.init_location = 127;
	//宿舍
//	module.init_location = 154;
	//食堂
//	module.init_location = 172;
	//教学楼
//	module.init_location = 109;

	return module;
});